"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const DBTool_1 = __importDefault(require("./DBTool"));
let DBList = [];
let connectTimer = null;
let scanningTimer = null;
function getMinuteDiff(startTime, endTime) {
    let start = new Date(startTime.replace(/-/g, '/'));
    let end = new Date(endTime.replace(/-/g, '/'));
    let diff = end.getTime() - start.getTime();
    return diff / (1000 * 60);
}
function openTimer() {
    if (connectTimer && scanningTimer)
        return;
    connectTimer && clearInterval(connectTimer);
    scanningTimer && clearInterval(scanningTimer);
    connectTimer = setInterval(() => {
        DBList.forEach((item) => {
            let now = new Date();
            let diff = getMinuteDiff(DBList[0].lastTile.toString(), now.toString());
            if (diff > 2) {
                item.dbTool.close().then();
                DBList[0].lastTile = now;
            }
        });
    }, 1000 * 60);
}
async function openDB(DBName, autoClose = false) {
    autoClose && openTimer();
    let DBItem = DBList.find(item => item.DBName === DBName);
    if (!DBItem) {
        const newDBItem = {
            DBName: DBName,
            dbTool: null,
            lastTile: new Date()
        };
        DBList.push(newDBItem);
        const dbTool = new DBTool_1.default(DBName);
        newDBItem.dbTool = dbTool;
        if (dbTool) {
            await dbTool.connect();
        }
        DBItem = newDBItem;
    }
    DBItem.lastTile = new Date();
    let dbTool = DBItem?.dbTool;
    return dbTool;
}
async function createDB(DBName) {
    const HasDB = await DBTool_1.default.HasDB(DBName);
    if (!HasDB) {
        let dbTool = new DBTool_1.default(DBName);
        await dbTool.connect();
        return dbTool;
    }
    else {
        await openDB(DBName);
    }
}
async function reConnect(DBName) {
    let DBItem = DBList.find(item => item.DBName === DBName);
    if (DBItem) {
        let dbTool = DBItem?.dbTool;
        if (dbTool)
            await dbTool.close();
        DBItem.dbTool = new DBTool_1.default(DBName);
        await DBItem.dbTool.connect();
        return DBItem.dbTool;
    }
    else {
        return await openDB(DBName);
    }
}
async function closeAll() {
    for (let i = 0; i < DBList.length; i++) {
        let dbTool = DBList[i].dbTool;
        if (dbTool)
            await dbTool.close();
    }
    DBList = [];
    connectTimer && clearTimeout(connectTimer);
    scanningTimer && clearTimeout(scanningTimer);
}
const DBConnectTool = {
    openDB,
    createDB,
    reConnect,
    closeAll
};
exports.default = DBConnectTool;
